package com.fzkj.juc.forkjoin.forkjoin2;

import com.fzkj.juc.forkjoin.entity.User;
import com.fzkj.juc.forkjoin.entity.UserContext;

import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * @ description
 * @ author yaya
 * @ since 2024/9/5
 */
public class UserRepeatRecursiveTask extends RecursiveTask<Boolean> {

    /**
     * 拆分的临界值
     */
    private static final long THRESHOLD = 2;

    private final List<User> data;

    public UserRepeatRecursiveTask(List<User> data) {
        System.out.println("data ->>" + data);
        this.data = data;
    }

    @Override
    protected Boolean compute() {
        long len = data.size();
        if (len < THRESHOLD) {
            // 判断重复的业务逻辑
            System.out.println("开始去冲 --> " + data);
            return UserContext.isExist(data.stream().map(User::getUserId).toList());
        }else {
            // 继续拆分
            long mid = data.size() / 2;
            // 左边的
            UserRepeatRecursiveTask left = new UserRepeatRecursiveTask(data.subList(0, (int) mid));
            left.fork();
            UserRepeatRecursiveTask right = new UserRepeatRecursiveTask(data.subList((int) mid, data.size()));
            right.fork();
            return left.join() && right.join();
        }
    }
}
